using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.IO;
using System.Data.SqlClient;

namespace Serialcoder.Erp.Tools.PatchCreator
{
	public partial class MainForm : Form
	{
        private MainForm()
		{
			InitializeComponent();
		}

        
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

            this.MainMenuStrip = menuStrip1;
			            
            ShowTemplates();
		}

        

        private void ShowTemplates()
        {
            uxTemplateToolStripSplitButton.DropDownItems.Clear();

            foreach (string key in Context.Current.Templates.Keys)
            {
                ToolStripButton button = new ToolStripButton(key);
                button.Name = key;
                button.DisplayStyle = ToolStripItemDisplayStyle.Text;
                button.Click += new EventHandler(OnTemplateButtonClick);

                uxTemplateToolStripSplitButton.DropDownItems.Add(button);
            }
        }

        void OnTemplateButtonClick(object sender, EventArgs e)
        {
            if (this.ActiveMdiChild != null)
            {
                (this.ActiveMdiChild as PatchForm).InsertTemplate((sender as ToolStripButton).Name);
            }
        }

		
		#region Execute sql file

		public void ExecuteSqlInFile(string pathToScriptFile, string connectionString)
		{
			SqlConnection connection;

			StreamReader _reader = null;

			string sql = "";

			if (false == System.IO.File.Exists(pathToScriptFile))
			{
				throw new Exception("File " + pathToScriptFile + " does not exists");
			}
			using (Stream stream = System.IO.File.OpenRead(pathToScriptFile))
			{
				_reader = new StreamReader(stream);

				connection = new SqlConnection(connectionString);

				SqlCommand command = new SqlCommand();

				connection.Open();
				command.Connection = connection;
				command.CommandType = System.Data.CommandType.Text;

				while (null != (sql = ReadNextStatementFromStream(_reader)))
				{
					command.CommandText = sql;

					command.ExecuteNonQuery();
				}

				_reader.Close();
			}
			connection.Close();
		}


		private static string ReadNextStatementFromStream(StreamReader _reader)
		{
			StringBuilder sb = new StringBuilder();

			string lineOfText;

			while (true)
			{
				lineOfText = _reader.ReadLine();
				if (lineOfText == null)
				{

					if (sb.Length > 0)
					{
						return sb.ToString();
					}
					else
					{
						return null;
					}
				}

				if (lineOfText.TrimEnd().ToUpper() == "GO")
				{
					break;
				}

				sb.Append(lineOfText + Environment.NewLine);
			}

			return sb.ToString();
		}

		#endregion

        private void OnOpenPatchClick(object sender, EventArgs e)
        {
            BrowsePatchForm form = new BrowsePatchForm();
            form.WindowState = FormWindowState.Normal;
            if (form.ShowDialog() == DialogResult.OK)
            {
                PatchForm form2 = new PatchForm();
                form2.Patch = Runtime.DAL.CreateNew();
                form2.MdiParent = this;
                form2.Patch = form.Patch;
                form2.Show();
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();

        }

        private void nouveauPatchToolStripMenuItem_Click(object sender, EventArgs e)
        {
			//PatchForm form = new PatchForm();
			//form.Patch = Runtime.DAL.CreateNew();
			//form.MdiParent = this;
			//form.WindowState = FormWindowState.Maximized;
			//form.Text = string.Format("Nouveau patch {0}", this.MdiChildren.Length);
			//form.Show();
			Context.Current.CreatePatch();
        }


		#region Singleton

		private static volatile MainForm _singleton;
		private static object syncRoot = new Object();

		public static MainForm Current
		{
			get
			{
				if (_singleton == null)
				{
					lock (syncRoot)
					{
						if (_singleton == null)
						{
							_singleton = new MainForm();
						}
					}
				}

				return _singleton;
			}
		}
		#endregion

	}
}